﻿using AiChiTu.TraceabilitySystem.Domain.AiChiTuManagement;
using AiChiTu.TraceabilitySystem.Domain.RBAC;
using AiChiTu.TraceabilitySystem.Domain.TestEntity;
using AiChiTu.TraceabilitySystem.ErrorCode;
using AiChiTu.TraceabilitySystem.ErrorCode.Extensions;
using AiChiTu.TraceabilitySystem.Infrastructure;
using AiChiTu.TraceabilitySystem.Read.API.Applications.Commands.Logins;
using AiChiTu.TraceabilitySystem.Read.API.Applications.Commands.Productbasicses;
using AiChiTu.TraceabilitySystem.Read.API.Applications.Commands.ProductNames;
using AiChiTu.TraceabilitySystem.Read.API.Dtos.Logins;
using AiChiTu.TraceabilitySystem.Read.API.Dtos.Productbasicses;
using CSRedis;
using MediatR;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.IdentityModel.Tokens;
using Newtonsoft.Json;
using static AiChiTu.TraceabilitySystem.Read.API.Controllers.ManagementReadController;
using static System.Net.Mime.MediaTypeNames;

namespace AiChiTu.TraceabilitySystem.Read.API.Controllers
{
	/// <summary>
	/// 读-信息管理控制器
	/// </summary>
	[Route("api/[controller]/[action]")]
	[ApiController]
	[Authorize]
	public class ManagementReadController : ControllerBase
	{
		/// <summary>
		/// 中介者
		/// </summary>
		private readonly IMediator mediator;
		private readonly DataDBContext db;

		/// <summary>
		/// 构造方法
		/// </summary>
		/// <param name="mediator">中介者</param>
		public ManagementReadController(IMediator mediator, DataDBContext db)
		{
			this.mediator = mediator;
			this.db = db;
		}
		/// <summary>
		/// 登录请求命令处理
		/// </summary>
		/// <param name="request">登录请求命令</param>
		/// <returns>返回任务</returns>
		[HttpPost]
		[AllowAnonymous]
		public async Task<APIResult<LoginDTO>> Login(LoginCommand request)
		{
			//// 连接Redis数据库
			//CSRedisClient cSRedisClient = new CSRedis.CSRedisClient("127.0.0.1:6379,defultDatabase=0");
			//// 将待存的数据转换为字符串数据 (序列化)
			//string? strLoginCommand = JsonConvert.SerializeObject(request);
			//// 将字符串存进Redis
			//cSRedisClient.Set("strLoginCommand", strLoginCommand,TimeSpan.FromMinutes(5));
			//// 从Redis中获取已存数据
			//string keyok = cSRedisClient.Get("strLoginCommand");
			//// 删除Redis里已有的数据
			//cSRedisClient.Del("strLoginCommand");
			//keyok = cSRedisClient.Get("strLoginCommand");
			//// 将已存的数据转换为指定的数据类型	(反序列化)
			//LoginCommand? result = JsonConvert.DeserializeObject<LoginCommand>(keyok);
			return await mediator.Send(request);
		}
		/// <summary>
		/// 分页查询商品基础信息请求
		/// </summary>
		/// <param name="request">分页查询商品基础信息请求命令</param>
		/// <returns>返回任务</returns>
		[HttpGet]
		public async Task<APIResult<APIPaging<QueryPageOfProductbasicDTO>>> QueryPageOfProductbasic([FromQuery] QueryPageOfProductbasicCommand request)
		{
			return await mediator.Send(request);
		}
		/// <summary>
		/// 查询全部商品名称请求
		/// </summary>
		/// <returns>返回任务</returns>
		[HttpGet]
		public async Task<APIResult<List<ProductName>>> QueryAllProductName()
		{
			return await mediator.Send(new QueryAllProductNameCommand());
		}
		/// <summary>
		/// 查询商品详情信息请求
		/// </summary>
		/// <param name="request">查询商品详情信息请求命令</param>
		/// <returns>返回任务</returns>
		[HttpGet]
		public async Task<APIResult<QueryProductbasicDetailsByIdDTO>> QueryProductbasicDetailsById([FromQuery]QueryProductbasicDetailsByIdCommand request)
		{
			return await mediator.Send(request);
		}

		/// <summary>
		/// 测试Redis: 设置Redis的值
		/// </summary>
		/// <returns>返回动作结果</returns>
		[HttpGet]
		public async Task<IActionResult> SetRedis()
		{
			// 判断Redis数据库里是否有 "TestInfos:SetRedisResult"
			List<TestInfo> result = RedisHelper.Get<List<TestInfo>>("TestInfos:SetRedisResult");
			// 如果不是空值,有已存的数据
			if (result.Count() > 0 && result != null)
			{
				return Ok(result);
			}
			// 从SQLserver数据库中查询全部测试表数据
			result = await db.Set<TestInfo>().ToListAsync();
			// 设定带有过期时间的Redis数据
			// TestInfos:SetRedisResult		创建 TestInfos 文件夹下的 SetRedisResult 数据变量
			// TimeSpan.FromMinutes(10)		十分钟后过期(自动删除)
			var random = new Random();
			// random.Next(0,10)			生成0-10之间的随机整数
			// random.NextDouble() * 10		生成0.00-10.00之间的随机浮动数
			await RedisHelper.SetAsync("TestInfos:SetRedisResult", result, TimeSpan.FromMinutes(random.NextDouble() * 10));
			return Ok(result);
		}
		/// <summary>
		/// 测试Redis: 添加测试表信息
		/// </summary>
		/// <param name="testInfo">实体</param>
		/// <returns>返回动作结果</returns>
		[HttpPost]
		public async Task<IActionResult> CreateTestInfo(TestInfo testInfo)
		{
			await db.Set<TestInfo>().AddAsync(testInfo);
			if (await db.SaveChangesAsync() > 0)
			{
				// 添加数据成功后,需要删除Redis的数据
				// 确保下次查询的时候,Redis从SQLserver数据库里更新新的数据
				await RedisHelper.DelAsync("TestInfos:SetRedisResult");
			}
			return Ok();
		}
	}
}
